package com.banshuibao.bsb_android.activity;

import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.ExpertAnswerAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AddressModel;
import com.banshuibao.bsb_android.model.ExpertListModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.ExpertTreeModel;
import com.banshuibao.bsb_android.model.RegionModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshListView;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.PopuWindowsUtil;
import com.banshuibao.bsb_android.util.XToast;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class ExpertsAnswerActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2, View.OnClickListener, AdapterView.OnItemClickListener {

    private PullToRefreshListView ptrlv;
    private ListView listView;
    private ExpertAnswerAdapter expertAnswerAdapter;
    private boolean isUp;
    private int startId, endId;
    private int rows;
    private LinearLayout indeustry, category, special, region;
    private TextView indeustry_tv, category_tv, special_tv, region_tv;
    private PopupWindow popupWindow;
    private ExpertTreeModel expertTreeModel;
    private AddressModel addressModel;
    private ImageView background_iv;
    private List<ExpertTreeModel.DataBean.ChildrenBean> tradeList;
    private List<ExpertTreeModel.DataBean.ChildrenBean> taxList;
    private List<ExpertTreeModel.DataBean.ChildrenBean> topicList;
    private List<AddressModel> list;
    private String type = "all";
    private String uuid = "";
    private TextView areaId_bt;
    private LinearLayout.LayoutParams params;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private ImageView search_iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_experts_answer);
        sp = getSharedPreferences("menuData", MODE_PRIVATE);
        initView();
        getTreeData();//菜单数据

        //  readData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    public void initView() {
        setTitleText("专家互动问答专区");
        areaId_bt = findViewById(R.id.menu);
        areaId_bt.setVisibility(View.VISIBLE);
        areaId_bt.setText("地区特殊规定");
        areaId_bt.setOnClickListener(this);
        search_iv = findViewById(R.id.search_iv);
        search_iv.setOnClickListener(this);
        /**
         * 筛选栏
         */
        indeustry = findViewById(R.id.industry);
        indeustry_tv = findViewById(R.id.industry_tv);
        category = findViewById(R.id.category);
        category_tv = findViewById(R.id.category_tv);
        special = findViewById(R.id.special);
        special_tv = findViewById(R.id.special_tv);
        //  region = findViewById(R.id.region);
        //   region_tv = findViewById(R.id.region_tv);
        indeustry.setOnClickListener(this);
        category.setOnClickListener(this);
        special.setOnClickListener(this);
        //     region.setOnClickListener(this);
        /**
         * 列表
         */
        background_iv = findViewById(R.id.backgroud_iv);
        ptrlv = findViewById(R.id.ptrlv);
        ptrlv.setMode(PullToRefreshBase.Mode.BOTH);
        ptrlv.setOnRefreshListener(this);
        listView = ptrlv.getRefreshableView();
        listView.setDivider(null);
        Drawable drawable = getResources().getDrawable(R.drawable.noloading);
        ImageView imageView = new ImageView(this);
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        imageView.setLayoutParams(params);
        imageView.setImageDrawable(drawable);
        listView.setEmptyView(imageView);
        expertAnswerAdapter = new ExpertAnswerAdapter(this, true);
        listView.setAdapter(expertAnswerAdapter);
        listView.setOnItemClickListener(this);
        list = new ArrayList<>();
    }

    /**
     * 设置数据
     */
    public void getData() {
        isUp = false;
        startId = 1;
        endId = startId + 9;
        if (expertAnswerAdapter != null) {
            int count = expertAnswerAdapter.getCount();
            if (count > 10) {
                endId += count - 10;
            }
        }
        requestNet();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        isUp = true;
        endId = startId + 9;
        requestNet();
    }


    public void getTreeData() {
        /**
         * 行业税种专题数据
         */
        HttpUtil.doPost(Constants.Url.EXPERT_TREE, null, new HttpResponse(this, ExpertTreeModel.class) {
            @Override
            public void onResult(Object obj) {
                expertTreeModel = (ExpertTreeModel) obj;
                List<ExpertTreeModel.DataBean> data = expertTreeModel.getData();
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getName().equals("行业")) {
                        tradeList = data.get(i).getChildren();
                    } else if (data.get(i).getName().equals("税种")) {
                        taxList = data.get(i).getChildren();
                    } else if (data.get(i).getName().equals("专题")) {
                        topicList = data.get(i).getChildren();
                    }
                }
            }
        });

        /**
         * 地区数据
         */
        HttpUtil.doPost(Constants.Url.EXPERT_ADDRESS, null, new HttpResponse(this, RegionModel.class) {
            @Override
            public void onResult(Object obj) {
                RegionModel regionModel = (RegionModel) obj;
                TreeMap<String, String> json = regionModel.getData();
                setAddress(json);
            }
        });
    }

    /**
     * 请求结果
     */
    public void requestNet() {
        ExpertListModel listModel = new ExpertListModel();
        listModel.setSinceId(startId);
        listModel.setMaxId(endId);
        listModel.setType(type);
        listModel.setUuid(uuid);
        HttpUtil.doPost(Constants.Url.EXPERT_ANSWER, listModel, new HttpResponse(this, ExpertResultModel.class) {
            @Override
            public void onResult(Object obj) {
                ExpertResultModel model = (ExpertResultModel) obj;
                rows = model.getRows();
                startId += rows;
                List<ExpertResultModel.DataBean> data = model.getData();
                if (isUp) {
                    expertAnswerAdapter.setUpData(data);
                } else {
                    expertAnswerAdapter.setDownDate(data);
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                ptrlv.onRefreshComplete();
            }
        });
    }


    /**
     * 默认值
     */
    public void defultData() {
        indeustry_tv.setText("行业");
        indeustry_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
        category_tv.setText("税种");
        category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
        special_tv.setText("专题");
        special_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
        //   region_tv.setText("地区");
        //    region_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
    }

    /**
     * 展示弹窗
     */
    public void showDialog(View view, List<ExpertTreeModel.DataBean.ChildrenBean> list, List<AddressModel> addressModelList, final TextView tv, final String type1) {
        PopuWindowsUtil popuWindowsUtil = new PopuWindowsUtil(this);
        if (list != null) {
            popupWindow = popuWindowsUtil.getP(list, null, "tree");
        } else if (addressModelList != null) {
            popupWindow = popuWindowsUtil.getP(null, addressModelList, "address");
        }
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                indeustry_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
                category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
                //   region_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
                special_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
            }
        });
        PopuWindowsUtil.showAsDropDown(popupWindow, view, 0, 0);
        popuWindowsUtil.setContent(new PopuWindowsUtil.ItemOnClickListener() {
            @Override
            public void getContent(String name, String uuid) {
                if (!TextUtils.isEmpty(name)) {
                    type = type1;
                    if (!TextUtils.equals("全部", name) && !TextUtils.equals("全国", name)) {
                        defultData();
                        tv.setText(name);
                        ExpertsAnswerActivity.this.uuid = uuid;
                    } else {
                        type = "all";
                        defultData();
                    }

                }
                //     saveDate(uuid, type, name);
                if (popupWindow != null) popupWindow.dismiss();
                getData();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null) popupWindow.dismiss();
        if (expertAnswerAdapter != null) {
            expertAnswerAdapter.clear();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.industry:
                indeustry_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                if (tradeList != null && tradeList.size() > 0) {
                    showDialog(view, tradeList, null, indeustry_tv, "trade");
                } else {
                    exception();
                }
                break;
            case R.id.category:
                category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                if (taxList != null && taxList.size() > 0) {
                    showDialog(view, taxList, null, category_tv, "tax");
                } else {
                    exception();
                }

                break;
            case R.id.special:
                special_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                if (topicList != null && topicList.size() > 0) {
                    showDialog(view, topicList, null, special_tv, "topic");
                } else {
                    exception();
                }

                break;
//            case R.id.region:
//                type = "area";
//                region_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
//                if (list != null && list.size() > 0) {
//                    showDialog(view, null, list, region_tv);
//                } else {
//                    exception();
//                }
//
//                break;
            case R.id.menu:
                IntentManager.goAreaIdActivity(ExpertsAnswerActivity.this);
                break;
            case R.id.search_iv:
                IntentManager.goSearchVoiceActivity(ExpertsAnswerActivity.this);
                break;
        }
    }

    public void setAddress(TreeMap<String, String> hashMap) {
        //遍历集合得到业务id+名称
        for (TreeMap.Entry<String, String> entry : hashMap.entrySet()) {
            list.add(new AddressModel(entry.getValue(), entry.getKey(), ""));
        }
    }

    public void exception() {
        defultData();
        getTreeData();
        XToast.showToast(ExpertsAnswerActivity.this, "获取数据失败，请检查网络");
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (expertAnswerAdapter != null && expertAnswerAdapter.getCount() > 0) {
            ExpertResultModel.DataBean dataBean = expertAnswerAdapter.getItem(i - 1);
            IntentManager.goExpertDetailActivity(ExpertsAnswerActivity.this, dataBean.getUuid());
        }
    }

    //读取存储值
    public void readData() {
        String type = sp.getString("type", "");
        String name1 = sp.getString("industry", "");
        String name2 = sp.getString("category", "");
        String name3 = sp.getString("special", "");
        String uuid = sp.getString("uuid", "");
        if (!TextUtils.equals(type, "all")) {
            this.uuid = uuid;
            if (TextUtils.equals(type, "trade")) {
                this.type = "trade";
                indeustry_tv.setText(name1);
            } else if (TextUtils.equals(type, "tax")) {
                this.type = "tax";
                category_tv.setText(name2);
            } else if (TextUtils.equals(type, "topic")) {
                this.type = "topic";
                special_tv.setText(name3);
            } else {
                this.type = "all";
                defultData();
            }
        }
        getData();
    }

    //保存数值
    public void saveDate(String uuid, String type, String name) {
        if (sp != null) {
            editor = sp.edit();
            if (TextUtils.equals(type, "all")) {
                editor.clear().commit();
                return;
            }
            editor.putString("uuid", uuid);
            if (TextUtils.equals(type, "trade")) {
                editor.putString("type", "trade");
                editor.putString("industry", name);
            } else if (TextUtils.equals(type, "tax")) {
                editor.putString("type", "tax");
                editor.putString("category", name);
            } else if (TextUtils.equals(type, "topic")) {
                editor.putString("type", "topic");
                editor.putString("special", name);
            }
            editor.commit();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (expertAnswerAdapter != null) {
            expertAnswerAdapter.stopMedia();
        }
    }


}
